﻿using Hangfire;
using Hangfire.Dashboard;
using Microsoft.Owin;
using Owin;
using System.Collections.Generic;
using System.Security.Claims;
using Yz.Base.Dal;
using Yz.Model.Constants;

namespace Yz.Manage
{
    public static partial class StartupExtension
    {
        public static void RegisterHangfire(this IAppBuilder app)
        {
            #region 定时程序 
            //Hangfire定时任务保存到数据库中
            GlobalConfiguration.Configuration
                .UseSqlServerStorage(DBConstant.HangfireConnStr);
            //Hangfire启用控制面板
            var options = new DashboardOptions
            {
                Authorization = new List<HangFireAuthorizationFilter> { new HangFireAuthorizationFilter() { } },
                AppPath = "/Home/Index" //返回应用链接
            };
            //app.UseHangfireDashboard();
            app.UseHangfireDashboard("/HangFire", options);
            #endregion 
        }
    }
    public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            var owinContext = new OwinContext(context.GetOwinEnvironment());
            // Allow all authenticated users to see the Dashboard (potentially dangerous).
            ClaimsPrincipal user = owinContext.Authentication.User;
            return user.Identity.IsAuthenticated && user.IsInRole(UserRoleName.System);
        }
    }
}